package builder;

import model.dao.accDAO;
import model.dao.defaultDAO;
import model.dto.accDTO;

import org.jdom.*;
import org.jdom.output.*;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class documentBuilder {
	
	
	public static void XMLBuilder(String userId) throws SQLException, IOException {
		ArrayList rankList = (ArrayList) accDAO.selectRank(userId);
		ArrayList defaultList = (ArrayList) defaultDAO.selectDefaultTagId();//DB(defaulttag)에있는 tagid 리스트
		ArrayList makeList = new ArrayList();//사용자 클릭 tagid를 여기다 넣을거임

		Iterator iter = rankList.iterator();
		while(iter.hasNext()){
			makeList.add(((accDTO)iter.next()).getTagId());   //사용자 클릭 tagid를 가지고있는 배열
		}
		System.out.println("makeList = "+makeList);
		 
		System.out.println("defaultList = "+defaultList);
		
		for(int i=0;i<defaultList.size();i++){
			if(!(makeList.contains(defaultList.get(i)))){
				makeList.add(defaultList.get(i));
			}
		}
		
		System.out.println("new makeList = "+makeList);
		System.out.println("new makeList size = "+makeList.size()+"  defaultList size = "+defaultList.size());
		
		Element rankTags = new Element("rankTags");
		
		for(int i=0; i<makeList.size(); i++){
			Element tagId = new Element("tagId");
			rankTags.addContent(tagId);
			String str = (String) makeList.get(i);
			tagId.setText(str);
		}
		
		Document doc = new Document(rankTags);

		XMLOutputter out = new XMLOutputter();
		Format f = out.getFormat();
		f.setEncoding("UTF-8");// 한글처리

		// 개행과 들여쓰기를 함께 해야함
		f.setLineSeparator("\n");// 개행
		f.setIndent("  ");// 들여쓰기
		f.setTextMode(Format.TextMode.TRIM);// Text에 의한 자동 줄바꿈해제
		FileWriter writer = null;
		try {
			writer = new FileWriter("D:/2.NHN/PROJECT_SPACE/6.RealProj/DB_ClickCount/WebContent/rank_"+userId+".xml");
			//D:/2.NHN/PROJECT_SPACE/6.RealProj/DB_ClickCount/WebContent/rank.xml
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		out.setFormat(f); // 새로운 Format으로 설정
		try {
			// out.output(doc, System.out);
			out.output(doc,writer);// 파일 생성됨   
		} catch (Exception e) {
			System.out.println("xml빌드 오류");
		}finally{
			writer.close();
		}
	}
}
